/*
* Created on 2014-11-04
* Copyright (c) 2001-2014 泛微软件
* 泛微协同商务系统，版权所有。
* 
*/

package weaver.alioss;

import weaver.alioss.AliOSSObjectUtil;
import weaver.conn.RecordSet;
import weaver.file.AESCoder;
import weaver.file.Prop;
import weaver.general.BaseBean;
import weaver.general.IpUtils;
import weaver.general.Util;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.zip.ZipInputStream;

/**
 * Description: 阿里云基本类
 * @author 方观生
 * @date 2014-11-04
 */

public class AliOSSObjectManager extends BaseBean {


	/**
	 * 构造函数
	 */
	public AliOSSObjectManager() {
		try {

		} catch (Exception ex) {
		}
	}

    /**
     * 上传文件到阿里云
     * @param filerealpath 文件存储路径
     * @param filename 文件名称
     * @param iszip 是否压缩
     * @param isaesencrypt 是否加密
     * @param aescode 加密串
     */		
	public void  uploadFile(final String filerealpath,final String filename,final String iszip,final String isaesencrypt,final String aescode){
		//判断阿里云工具类能否正常加载
		if(!isexistAliOSSObjectUtil()){
			return ;
		}		
		//判断是否启用了阿里云
		if(!AliOSSObjectUtil.isEnable()){
			return ;
		}
		
		try {
			if(isonlyAliOSS()){
				uploadFileThread(filerealpath, filename, iszip, isaesencrypt,aescode);				
			}else{
				new Thread(new Runnable() {
					public void run() {
						uploadFileThread(filerealpath, filename, iszip, isaesencrypt,aescode);
					}
				}).start();				
			}

		} catch (Exception ex) {
		}				
	}
    /**
     * 上传文件到阿里云  线程方法
     * @param filerealpath 文件存储路径
     * @param filename 文件名称
     * @param iszip 是否压缩
     * @param isaesencrypt 是否加密
     * @param aescode 加密串
     */		
	private void uploadFileThread(String filerealpath,String filename,String iszip,String isaesencrypt,String aescode){

		 InputStream imagefile = null;
		try {
			String tokenKey=this.getTokenKeyByFileRealPath(filerealpath);
            File thefile = new File(filerealpath) ;

            if(iszip.equals("1")) {
                ZipInputStream zin = new ZipInputStream(new FileInputStream(thefile)) ;
                if(zin.getNextEntry() != null)
                    imagefile = new BufferedInputStream(zin);
            } else{
                imagefile = new BufferedInputStream(new FileInputStream(thefile)) ;
            }			
			if(isaesencrypt.equals("1")){
				imagefile = AESCoder.decrypt(imagefile, aescode);
			}  
	        AliOSSObjectUtil.autoUploadFile(tokenKey, filename,imagefile);	
        
		} catch (Exception ex) {
		}finally{			
            try{
            	if(imagefile!=null){
            		imagefile.close() ;
            	}
            }catch(Exception ex){
            }          
		}
	}
    /**
     * 根据文件存储路径获取存储Key
     * @param filerealpath 文件存储路径
     * @return 存储Key
     */	
	public  static String getTokenKeyByFileRealPath(String filerealpath){
		String tokenKey="";
		try {
			if(filerealpath==null||filerealpath.trim().equals("")){
				return tokenKey;
			}
        	int i = filerealpath.lastIndexOf("/");
        	int j = filerealpath.lastIndexOf("\\");			
        	int index = i >j?i:j;
        	if(index<0){
				return tokenKey;        		
        	}
        	int point = 0;        	
        	String tempstr = filerealpath.substring(index,filerealpath.length());
        	if(tempstr.indexOf(".")!=-1){
        		point = index + tempstr.lastIndexOf(".");
        	}else{
        		point = filerealpath.length();
        	}
        	tokenKey = filerealpath.substring(index-8,point)+".wfile";
        	tokenKey = tokenKey.replaceAll("\\\\", "/");       	
        	
		} catch (Exception ex) {
		}				
		return tokenKey;
	}
	
    /**
     * 判断当前用户是否通过云盘查看文档
     * @param req 页面请求信息
     * @return 是否能够通过云盘查看文档
     */		
	public  static boolean isEnableForDsp(HttpServletRequest req){
		boolean isEnableForDsp=false;
		try {
			if(!isexistAliOSSObjectUtil()){
				return isEnableForDsp;
			}
			boolean isEnable=AliOSSObjectUtil.isEnable();
			if(!isEnable){
				return isEnableForDsp;
			}
			String ip=Util.getIpAddr(req);
			boolean checktmp = checkIpInner(ip);
			if(isEnable&&(!checktmp)){
				isEnableForDsp=true;
			}
			
		} catch (Exception ex) {
		}				
		return isEnableForDsp;		
	}
	
    /**
     * 判断该附件能否通过云盘查看
     * @param imageFileId 附件id
     * @return 是否能够通过云盘查看文档
     */		
	public  static boolean isEnableForImageFile(int imageFileId){
		boolean isEnableForImageFile=false;
		try {
			String tokenKey="";
			String storageStatus="";
			RecordSet rs=new RecordSet();
			rs.executeSql("select TokenKey,StorageStatus from ImageFile where imageFileId="+imageFileId);
			if(rs.next()){
				tokenKey=Util.null2String(rs.getString("TokenKey"));
				storageStatus=Util.null2String(rs.getString("StorageStatus"));
			}
			if(!tokenKey.equals("")&&storageStatus.equals("1")){
				isEnableForImageFile=true;
			}
		} catch (Exception ex) {
		}				
		return isEnableForImageFile;		
	}	

    /**
     * 根据附件id获取tokenKey
     * @param imageFileId 附件id
     * @return tokenKey    注：storageStatus不为1时tokenKey为空
     */		
	public  static String getTokenKeyByImageFileId(int imageFileId){
		String tokenKey="";
		try {
			String storageStatus="";
			RecordSet rs=new RecordSet();
			rs.executeSql("select TokenKey,StorageStatus from ImageFile where imageFileId="+imageFileId);
			if(rs.next()){
				tokenKey=Util.null2String(rs.getString("TokenKey"));
				storageStatus=Util.null2String(rs.getString("StorageStatus"));
			}
			if(!storageStatus.equals("1")){
				tokenKey="";
			}
		} catch (Exception ex) {
		}				
		return tokenKey;		
	}
	
	/**
	 * 判断网址是否为内网地址
	 * @param ipaddress
	 * @return boolean  true :是     false:否
	 */
	private static boolean checkIpInner(String ipaddress) {		
		boolean checktmp = false;
		String isInner = Util.null2String(Prop.getPropValue("alioss","isInner"));
		if(isInner.equals("false")){
			return checktmp;
		}
		
		ipaddress=Util.null2String(ipaddress);
		long ipNum = IpUtils.ip2number(ipaddress);    
		long a1=IpUtils.ip2number("10.0.0.0");
		long a2=IpUtils.ip2number("10.255.255.255");
		long b1=IpUtils.ip2number("172.16.0.0");
		long b2=IpUtils.ip2number("172.31.255.255");       
		long c1=IpUtils.ip2number("192.168.0.0");
		long c2=IpUtils.ip2number("192.168.255.255");
		
		if(isInner(ipNum,a1,a2) || isInner(ipNum,b1,b2) || isInner(ipNum,c1,c2) || ipaddress.equals("127.0.0.1")){
			checktmp=true;
		}
		
        return checktmp;
	}
	
	private static boolean isInner(long userIp,long begin,long end){
	    return (userIp>=begin) && (userIp<=end);
	}
	
	
    /**
     * 判断当前用户是否通过Safari浏览器查看文档
     * @param req 页面请求信息
     * @return isEnableForDsp
     */		
	public  static boolean isSafari(HttpServletRequest req){
		boolean isSafari=false;
		try {
			String  userAgent=Util.null2String(req.getHeader("USER-AGENT"));
			if(userAgent.indexOf("Safari") > -1 && userAgent.indexOf("Chrome") < 1 && userAgent.indexOf("Edge") < 1){
				isSafari=true;
			}
			
		} catch (Exception ex) {
		}				
		return isSafari;		
	}
    /**
     * 判断阿里云工具类能否正常加载
     * @return isexist   
     */			
	public  static boolean isexistAliOSSObjectUtil(){
		boolean isexist= true;
		try{    
			Class.forName("weaver.alioss.AliOSSObjectUtil");
		}catch(ExceptionInInitializerError e){
			isexist = false;	//判断云存储是否正常
		}catch(IllegalArgumentException e){
			isexist = false;	//判断云存储是否正常
		}catch(NoClassDefFoundError e){
			isexist = false;	//判断云存储是否正常
		}catch(Exception e){ 
			isexist = false;	//判断云存储是否正常
		}
		return isexist;
	}
	
    /**
     * 判断是否将数据流传输到服务器再下载
     * 
     * @return isexist   
     */			
	public  static boolean isAliOSSToServer(String comefrom){
		boolean isAliOSSToServer= false;
		if(comefrom==null||comefrom.trim().equals("")){
			return isAliOSSToServer;
		}
		try{
			//判断阿里云工具类能否正常加载
			if(!isexistAliOSSObjectUtil()){
				return isAliOSSToServer;
			}		
			//判断是否启用了阿里云
			if(!AliOSSObjectUtil.isEnable()){
				return isAliOSSToServer;
			}			

			//判断是否配置的是阿里云的内网地址
			if(AliOSSObjectUtil.getAliossServerAddress().contains("internal.aliyuncs")){
				isAliOSSToServer =  true;
			}

			String AliOSSToServerComeFrom = Util.null2String(Prop.getPropValue("alioss","AliOSSToServerComeFrom"));
			if(AliOSSToServerComeFrom.trim().equals("")){
				AliOSSToServerComeFrom="WorkflowToDoc";
			}
			if((","+AliOSSToServerComeFrom+",").indexOf(","+comefrom+",")>=0){
				isAliOSSToServer=true;
			}
			
		}catch(Exception e){ 
			isAliOSSToServer = false;	//判断云存储是否正常
		}
		return isAliOSSToServer;
	}

    /**
     * 判断是否仅启用阿里云
     * 
     * @return true:   
     */			
	public  static boolean isonlyAliOSS(){
		boolean isonlyAliOSS= false;

		try{
			//判断阿里云工具类能否正常加载
			if(!isexistAliOSSObjectUtil()){
				return isonlyAliOSS;
			}		
			//判断是否启用了阿里云
			if(!AliOSSObjectUtil.isEnable()){
				return isonlyAliOSS;
			}				
			
			String onlyAliOSS = Util.null2String(Prop.getPropValue("alioss","onlyAliOSS"));
			if(onlyAliOSS.trim().equals("1")){
				isonlyAliOSS=true;
			}
		}catch(Exception e){ 
			isonlyAliOSS = false;	//判断云存储是否正常
		}
		return isonlyAliOSS;
	}
	
    /**
     * 是否启用阿里云oss服务
     * @return
     */
    public static boolean isEnable(){
    	boolean isEnable=false;
		//判断阿里云工具类能否正常加载
		if(!isexistAliOSSObjectUtil()){
			return isEnable;
		}	    	
    	isEnable=Prop.getPropValue("alioss","status").equalsIgnoreCase("1");
    	return  isEnable;
    }	
	
}